import axios from 'axios';
import type { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';
import useUserStore from '@/store/modules/user';
import { showMessage } from './status';
//创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
});
//请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers.token = userStore.token;
    }
    const isFormData = config.data instanceof FormData;
    // FormData数据不做处理
    if (config.method === 'post' && !isFormData) {
      config.data = {
        ...config.data,
        requestId: String(Date.now()),
      };
    } else if (config.method === 'get') {
      config.params = {
        ...config.params,
        requestId: String(Date.now()),
      };
    }
    return config;
  },
  (error: AxiosError) => {
    console.log('-----请求发送错误-----');
    return Promise.reject(error);
  },
);
//响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status !== 200) {
      showMessage(response.statusText);
    }
    return response.data;
  },
  (error) => {
    //处理网络错误
    const status = error.response?.status;
    // 请求已发出，但是不在2xx的范围, 且不是文件上传接口触发的(场景: 上传过程中关闭弹窗触发的错误)
    if (error.code !== 'ERR_CANCELED' && !error.config.url?.includes('/file/upload-split')) {
      showMessage(status);
    }
    return Promise.reject(error);
  },
);
export default request;
